﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

using Vector2 = Microsoft.Xna.Framework.Vector2;

namespace LevelEditor
{
    public class DirectionPicker : Panel
    {
        private Vector2 _value;
        /// <summary>
        /// The direction chosen my the user
        /// </summary>
        public Vector2 Value
        {
            get { return _value; }

            set 
            {
                _value = value;
                // raise the value changed event
                if (ValueChanged != null)
                    ValueChanged(this, new EventArgs());
            }
        }

        public event EventHandler ValueChanged;

        public DirectionPicker()
        {
            this.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            Paint += DirectionPicker_Paint;
            Resize += DirectionPicker_Resize;
            MouseDown += DirectionPicker_MouseDown;
            MouseMove += DirectionPicker_MouseMove;
            DoubleBuffered = true;
        }

        void DirectionPicker_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                Value = new Vector2(e.Location.X - Width / 2, e.Location.Y - Height / 2);
                Invalidate(); 
            }
        }

        void DirectionPicker_MouseDown(object sender, MouseEventArgs e)
        {
            Value = new Vector2(e.Location.X - Width / 2, e.Location.Y - Height / 2);
            Invalidate();
        }

        void DirectionPicker_Resize(object sender, EventArgs e)
        {
            // ensure the control is always a perfect square
            Height = Width;
        }

        void DirectionPicker_Paint(object sender, PaintEventArgs e)
        {
            System.Drawing.Graphics g = e.Graphics;


            // draw smaller grid lines every ten pixels
            for (int i = 0; i < Width; i += 10)
            {
                g.DrawLine(Pens.Gray, new Point(i, 0), new Point(i, Height));
                g.DrawLine(Pens.Gray, new Point(0, i), new Point(Width, i));
            }

            Pen p = new Pen(Brushes.Black);
            p.Width = 5.0f;

            // draw the lines that represent the x and y axis
            g.DrawLine(p, new Point(Width / 2, 0), new Point(Width / 2, Height));
            g.DrawLine(p, new Point(0, Height / 2), new Point(Width, Height / 2));

            

            // represent 'value' with a red dot
            g.FillEllipse(Brushes.Red, new RectangleF(_value.X - 2.5f + (Width / 2), _value.Y - 2.5f + (Height / 2), 5.0f, 5.0f));
        }
    }
}